﻿namespace Oddo.Concept.Crm.Repository.Common.Contracts
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using Oddo.Concept.Crm.Common.Communication.Interfaces;
    using Oddo.Concept.Crm.Common.Services;
    using Oddo.Concept.Crm.Models;

    public interface IRepositoryServices
    {
        IFindResponse<Country> FindCountries(CountryFindRequest request);

        Task<IFindResponse<Country>> FindCountriesAsync(CountryFindRequest request, CancellationToken cancellationToken);
    }


    public class RepositoryServicesClient : ServiceClientBase, IRepositoryServices
    {
        public RepositoryServicesClient(string serverHost, string baseUrl) 
            : base(serverHost,baseUrl)
        {
        }

        public IFindResponse<Country> FindCountries(CountryFindRequest request)
        {
            return SendRequest<CountryFindRequest, CountryFindResponse>(request, CancellationToken.None);
        }

        public Task<IFindResponse<Country>> FindCountriesAsync(CountryFindRequest request, CancellationToken cancellationToken)
        {
            return Task<IFindResponse<Country>>.Factory
                .StartNew(() =>
                    {
                        try
                        {
                            return SendRequest<CountryFindRequest, CountryFindResponse>(request, cancellationToken);
                        }
                        catch (OperationCanceledException)
                        {
                            Debug.WriteLine("Operation canceled");
                            return null;
                        }
                    }, cancellationToken);
        }
    }
}